package blogsys.demo.log;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

@Configuration
@Aspect
public class Log4j2 {
    private static final Logger logger = LogManager.getLogger(Log4j2.class);

    @Around("execution(public * blogsys.demo.server.impl.*.*(..))")
    public Object around(ProceedingJoinPoint call) throws Throwable {
        Object result = null;
        //取得类名和方法名
        String className = call.getTarget().getClass().getName();
        String methodName = call.getSignature().getName();

        //相当于前置通知
        logger.info(className+"：类的"+methodName+"方法开始执行");

        try {
            result = call.proceed();
            //相当于后置通知
            logger.info(className+"."+methodName+"()方法正常执行结束");

        } catch (Throwable e) {
            //相当于异常抛出后通知
            StackTraceElement stackTraceElement= e.getStackTrace()[e.getStackTrace().length-1];
            Object[] args=call.getArgs();

            logger.error("----------------------------------------------------------------------------------");
            logger.error ( "===执行{}类的{}()方法的{}行",className,methodName,stackTraceElement.getLineNumber());
            logger.error("===异常信息为：{}  ",e.fillInStackTrace().toString());
            logger.error("===参数信息为：{}  ",args);
            throw e;

        }finally{
            //相当于最终通知
            logger.info(className+"类的" +methodName+"方法执行结束");
        }
        return result;
    }
}
